<template>
  <div style="padding: 10px 0">
    <el-input placeholder="请输入部门名" style="width: 200px" :suffix-icon="Search"
              v-model="UnitName"></el-input>
    <el-input placeholder="请输入版本号" style="width: 200px" :suffix-icon="DocumentChecked" class="ml-5"
              v-model="VersionNum"></el-input>
    <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
    <el-button type="warning" @click="reset">重置</el-button>
  </div>
  <div style="margin: 10px 0">
    <el-button type="primary" @click="handleAdd">新增<i class=" el-icon-circle-plus-outline"></i>
    </el-button>
    <el-button type="danger" :icon="Delete" @click="open1" class="del">批量删除<i class=" el-icon-remove-outline"></i>
    </el-button>
  </div>
  
  <el-table
      :data="CityInfo"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :row-style="tableRowClassName"
      :default-sort="{ prop: 'uintID', order: 'ascending' }"
  >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="unitChnName" label="使用单位中文名称" width="400"/>
    <el-table-column prop="unitEngName" label="使用单位英文名称"/>
    <el-table-column prop="versionNum" label="平台版本号" width="100"/>
    <el-table-column prop="departEmail" label="邮箱" width="100"/>
    <el-table-column prop="departPhone" label="电话" width="100"/>
    <el-table-column prop="cntAdd" label="地址"/>
    <el-table-column prop="isUse" label="是否投入正常运行" width="160"/>
    <el-table-column label="操作" width="200" align="center">
      <template #default="scope">
        <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.uintID)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  
  <div class="pagination-block">
    <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  
  <el-dialog :title="title" v-model="dialogCityFormVisible">
    <el-form ref="userForm" :model="form" :rules="rules">
      <el-form-item label="使用单位中文名称" :label-width="formLabelWidth" prop="unitChnName">
        <el-input v-model="form.unitChnName"></el-input>
      </el-form-item>
      <el-form-item label="使用单位英文名称" :label-width="formLabelWidth" prop="unitEngName">
        <el-input v-model="form.unitEngName"></el-input>
      </el-form-item>
      <el-form-item label="平台版本号" :label-width="formLabelWidth" prop="versionNum">
        <el-input v-model="form.versionNum"></el-input>
      </el-form-item>
      <el-form-item label="部门邮箱地址" :label-width="formLabelWidth" prop="departEmail">
        <el-input v-model="form.departEmail"></el-input>
      </el-form-item>
      <el-form-item label="部门电话" :label-width="formLabelWidth" prop="departPhone">
        <el-input v-model="form.departPhone"></el-input>
      </el-form-item>
      <el-form-item label="是否投入正常运行" :label-width="formLabelWidth" prop="isUse">
        <el-radio-group v-model="form.isUse">
          <el-radio label="是"/>
          <el-radio label="否"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogCityFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {Search, DocumentChecked, Delete, Message} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import type {FormRules, FormInstance} from 'element-plus'
import axios from "axios";

const VersionNum = ref('')
const UnitName = ref('')
const formLabelWidth = '140px'
const title = ref('')

const CityInfo = ref([])
let dialogCityFormVisible = ref(false)
let total = ref(1)
let form = ref({})
const open1 = () => {
  ElMessageBox.alert('确定批量删除吗？', '', {
    confirmButtonText: '确定',
    showCancelButton: true,
    cancelButtonText: '我再想想',
    type: "warning"
  }).then(() => {
    delBatch();
  }).catch(() => {
    ElMessage.info("已取消删除")
  })
}
const handleAdd = () => {
  title.value = '新增使用单位'
  dialogCityFormVisible.value = true
  form.value = {}
}

const load = () => {
  axios.get('http://localhost:8080/cityinfo/page',{
    params: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      versionNum: VersionNum.value,
      UnitName: UnitName.value
    }
  })
      .then(
          res => {
            if (res.data.records){
              res.data.records.forEach((item: []) => {
                if (item.isUse == true) {
                  item.isUse = "是"
                } else item.isUse = "否"
              })
            }
            CityInfo.value = res.data.records
            total.value = parseInt(res.data.total)
            // console.log(res)
          }

      ).catch(e =>{
          console.log(e)
  })
}
onMounted(() => {
  load();
})
const ids = ref([])
const handleSelectionChange = (val: any) => {
  ids.value = val.map((item:any) => item.uintID)
  // console.log(ids.value)
};
const delBatch = () => {
  axios.post('http://localhost:8080/cityinfo/page').then(res => {
    if (res) {
      ElMessage.success("批量删除成功")
      load()
    } else {
      ElMessage.warning("批量删除失败")
    }
  })
};
const userForm = ref(null)
const save =  async () => {
  await userForm.value.validate((valid: boolean) => {
    if (valid) {
      if (form.value.isUse == '是') {
        form.value.isUse = true
      } else form.value.isUse = false
      axios.post('http://localhost:8080/cityinfo', form.value).then(res => {
        if (res) {
          ElMessage.success("保存成功")
          dialogCityFormVisible.value = false;
          userForm.value.resetFields()
          load()
        } else {
          ElMessage.warning("保存失败")
        }
      })
    } else {
      ElMessage.warning( "请修改正确的数据格式！");
    }
  })
}
const pageSize = ref(10)
const pageNum = ref(1)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const reset = () => {
  VersionNum.value = ''
  UnitName.value = ''
  load()
}
const del = (unitID) => {
  axios.delete('http://localhost:8080/cityinfo/' + unitID).then(res => {
    if (res) {
      ElMessage.success("删除成功")
      load()
    } else {
      ElMessage.error("删除失败")
    }
  }).catch(err =>{
    ElMessage.error("删除失败")
  })
}
const handleEdit = (row) => {
  // console.log(row)
  title.value = '编辑当前使用单位'
  dialogCityFormVisible.value = true
  form =  ref(row)
}


const rules = reactive<FormRules>({
  unitChnName: [
    {required: true, message: "请输入正确的中文名称", trigger: "blur",pattern:/[\u4e00-\u9fa5]/}
  ],
  unitEngName: [
    {required: true, message: "请输入正确的英文名称", trigger: "blur",pattern:/\b[A-Za-z]*\w\w\b/}
  ],
  versionNum: [
    {required: true, message: "请输入正确的平台版本号", trigger: "blur",pattern:/^[0-9]*$/}
  ],
  isUse: [
    {required: true, message: "是否投入正常运行不能为空", trigger: "change"}
  ],
  departPhone: [
    {required: true, message: "请输入正确的手机号", trigger: "blur",min: 12,max: 12,pattern:/^(0[1-9]{2,3}-?)?[2-9][0-9]{6,7}$/}
  ],
  departEmail: [
    {required: true, message: "请输入正确的邮箱号", trigger: 'blur',pattern:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/}
  ]
})

const tableRowClassName = ({
                             row
                           }: {
  row: any
}) => {
  if (row.isUse === "否") {
    return {
      backgroundColor: '#fdf6ec'
    }
  } else if (row.isUse === "是") {
    return {
      backgroundColor: '#f0f9eb'
    }
  }
  return ''
}
</script>


<style scoped>
.ml-5 {
  margin-left: 10px;
}

.pagination-block {
  margin-left: 25%;
}
</style>